package org.jeecg.modules.demo.navigation.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.navigation.entity.Information;
import org.jeecg.modules.demo.navigation.entity.Navigation;
import org.jeecg.modules.demo.navigation.vo.NavigationPage;
import org.jeecg.modules.demo.navigation.service.INavigationService;
import org.jeecg.modules.demo.navigation.service.IInformationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;

 /**
 * @Description: 导航栏
 * @Author: jeecg-boot
 * @Date:   2019-09-18
 * @Version: V1.0
 */
@RestController
@RequestMapping("/navigation/navigation")
@Slf4j
public class NavigationController {
	@Autowired
	private INavigationService navigationService;
	@Autowired
	private IInformationService informationService;

	 /**
	  * 更改点击量
	  * @
	  *
	  * @return
	  */
	 @RequestMapping(value = "/updateVisitsById", method = RequestMethod.POST)
	 public Result<?>  updateVisitsById(String id) throws Exception {
		 Result<?> result=new Result<>();
		 try{
			 Boolean b=informationService.updateVisitsById(id);
			 if (b=false){
				 result.error500("更新失败");
				 result.setMessage("更新失败");
			 }
			 else {
				 result.setMessage("更新成功");
				 result.error500("更新成功");
			 }
		 }catch (Exception e){
			 e.printStackTrace();
		 }
		 return result;
	 }
	 /**
	  * 更改通知状态
	  * @
	  *
	  * @return
	  */
	 @RequestMapping(value = "/updateStateById", method = RequestMethod.POST)
	 public Result<?>  updateStateById(String id,String state) throws Exception {
	 	Result<?> result=new Result<>();
	 	try{
			Boolean b=informationService.updateStateById(id,state);
			if (b=false){
				result.error500("更新失败");
				result.setMessage("更新失败");
			}
			else {
				result.setMessage("更新成功");
				result.error500("更新成功");
			}
		}catch (Exception e){
	 		e.printStackTrace();
	 	}
		 return result;
	 }


     /**
      * 分页列表查询
      * @
      *
      * @return
      */
     @RequestMapping(value = "/queryPageTypeList", method = RequestMethod.POST)
     public Result<List<Information>> queryPageTypeList(String typeStr,String upage) throws Exception {
         int nPage = Integer.valueOf(upage);
         int noPage=0;
         int sizePage=10;
         Result<List<Information>> result = new Result<List<Information>>();
         if (nPage <= 0) {
             throw new Exception("参数npage小于零");
         } else {
             List<Information> list = informationService.getInformationPageByType(typeStr,nPage,noPage,sizePage);
             result.setSuccess(true);
             result.setResult(list);
             result.setCode(informationService.getTypeCount(typeStr));
         }
         return result;
     }
	/*
	* 查询*/

	 @RequestMapping(value = "/getList", method = RequestMethod.POST)
//	@GetMapping(value = "/getList" , method = RequestMethod.POST)
	 public Result<List<Navigation>> getList(String typeStr) {
		 Result<List<Navigation>> result = new Result<List<Navigation>>();
		 try{
             if (typeStr==null||typeStr.equals("")) {
                 log.error("传参为空");
                 result.error500("传参为空");
             }
			 List<Navigation> list = navigationService.queryListCode(typeStr);
             if (list!=null) {
                 result.setSuccess(true);
                 result.setResult(list);
             }
		     }catch (Exception e){
		     e.printStackTrace();
             }
		 return result;
	 }
	
	/**
	  * 分页列表查询
	 * @param navigation
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<Navigation>> queryPageList(Navigation navigation,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<Navigation>> result = new Result<IPage<Navigation>>();
		QueryWrapper<Navigation> queryWrapper = QueryGenerator.initQueryWrapper(navigation, req.getParameterMap());
		Page<Navigation> page = new Page<Navigation>(pageNo, pageSize);
		IPage<Navigation> pageList = navigationService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param navigationPage
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<Navigation> add(@RequestBody NavigationPage navigationPage) {
		Result<Navigation> result = new Result<Navigation>();
		try {
			Navigation navigation = new Navigation();
			BeanUtils.copyProperties(navigationPage, navigation);
			
			navigationService.saveMain(navigation, navigationPage.getInformationList());
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param navigationPage
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<Navigation> edit(@RequestBody NavigationPage navigationPage) {
		Result<Navigation> result = new Result<Navigation>();
		Navigation navigation = new Navigation();
		BeanUtils.copyProperties(navigationPage, navigation);
		Navigation navigationEntity = navigationService.getById(navigation.getId());
		if(navigationEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = navigationService.updateById(navigation);
			navigationService.updateMain(navigation, navigationPage.getInformationList());
			result.success("修改成功!");
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			navigationService.delMain(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<Navigation> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<Navigation> result = new Result<Navigation>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.navigationService.delBatchMain(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<Navigation> queryById(@RequestParam(name="id",required=true) String id) {
		Result<Navigation> result = new Result<Navigation>();
		Navigation navigation = navigationService.getById(id);
		if(navigation==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(navigation);
			result.setSuccess(true);
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryInformationByMainId")
	public Result<List<Information>> queryInformationListByMainId(@RequestParam(name="id",required=true) String id) {
		Result<List<Information>> result = new Result<List<Information>>();
		List<Information> informationList = informationService.selectByMainId(id);
		result.setResult(informationList);
		result.setSuccess(true);
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, Navigation navigation) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<Navigation> queryWrapper = QueryGenerator.initQueryWrapper(navigation, request.getParameterMap());
      List<Navigation> queryList = navigationService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<Navigation> navigationList = new ArrayList<Navigation>();
      if(oConvertUtils.isEmpty(selections)) {
    	  navigationList = queryList;
      }else {
    	  List<String> selectionList = Arrays.asList(selections.split(","));
    	  navigationList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }
	  // Step.2 组装pageList
      List<NavigationPage> pageList = new ArrayList<NavigationPage>();
      for (Navigation main : navigationList) {
          NavigationPage vo = new NavigationPage();
          BeanUtils.copyProperties(main, vo);
          List<Information> informationList = informationService.selectByMainId(main.getId());
          vo.setInformationList(informationList);
          pageList.add(vo);
      }
      // Step.3 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "导航栏列表");
      mv.addObject(NormalExcelConstants.CLASS, NavigationPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("导航栏列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<NavigationPage> list = ExcelImportUtil.importExcel(file.getInputStream(), NavigationPage.class, params);
              for (NavigationPage page : list) {
                  Navigation po = new Navigation();
                  BeanUtils.copyProperties(page, po);
                  navigationService.saveMain(po, page.getInformationList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
